﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Data.Common;
using DataAccessor.Exceptions;

namespace DataAccessor
{
    /// <summary>
    /// 数据访问接口
    /// </summary>
    public abstract partial class IDataAccessor
    {
        /// <summary>
        /// 开始事务
        /// </summary>
        /// <param name="level">事务级别</param>
        /// <param name="transName">事务名称</param>
        public virtual DbTransaction BeginTransactoin(IsolationLevel level)
        {
            DbConnection conn = CreateConnection();
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            return conn.BeginTransaction(level);
        }

        /// <summary>
        /// 开始事务
        /// </summary>
        public virtual DbTransaction BeginTransactoin()
        {
            return BeginTransactoin(IsolationLevel.ReadCommitted);
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public virtual void CommitTransaction(DbTransaction trans)
        {
            if (trans == null)
            {
                return;
            }

            try
            {
                // 提交
                trans.Commit();
                trans.Dispose();
                trans = null;
            }
            catch
            {
                // 处理异常
                throw;
            }
        }

        /// <summary>
        /// 放弃事务
        /// </summary>
        public virtual void DropTransaction(DbTransaction trans)
        {
            if (trans == null)
            {
                return;
            }

            try
            {
                trans.Rollback();
            }
            catch
            {
                throw;
            }
            finally
            {
                trans.Dispose();
                trans = null;
            }
        }
    }
}
